package club.calong.sanniu.util;

import club.calong.sanniu.pojo.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.UUID;

@Component
public class JwtTokenUtil {

	@Value("${app.token-timeout}")
	Long TOKEN_TIMEOUT;

	public String createToken(User user) {

		LocalDateTime localDateTime = LocalDateTime.now().plusSeconds(TOKEN_TIMEOUT);
		Date expireTime = Date.from(localDateTime.toInstant(ZoneOffset.ofHours(8)));
		JwtBuilder jwtBuilder = Jwts.builder()
				.setId(UUID.randomUUID().toString()) // jwt的id
				.claim("user", user)// 载荷
				.setSubject("FX_开发_SPRING-BOOT") // 设置主题
				.setIssuedAt(Date.from(localDateTime.toInstant(ZoneOffset.ofHours(8)))) // 设置颁发时间
				.setExpiration(expireTime) // 设置过期时间
				.signWith(SignatureAlgorithm.HS256, "fx-execution"); // 设置加密方式和签名

		return jwtBuilder.compact();
	}

	public Claims verifyToken(String token) {
		Claims claims = null;
		try {
			claims = Jwts.parser()
							 .setSigningKey("fx-execution")
							 .parseClaimsJws(token)
							 .getBody();
		} catch (Exception e) {
			// 验证token可能出现异常
			// jwt过期可能会报 io.jsonwebtoken.ExpiredJwtException
			e.printStackTrace();
		}
		return claims;
	}
}

